import { _decorator, Component, Animation, Sprite, UITransform, animation, AnimationClip, Vec3, SpriteFrame } from 'cc';
import { ENTITY_STATE_ENUM, PARAMS_NAME_ENUM, ENTITY_TYPE_ENUM, SPIKES_TYPE_MAP_TOTAL_COUNT_ENUM, EVENT_ENUM } from '../../Enums';
import { TILE_WIDTH, TILE_HEIGHT } from '../../Scripts/Tile/TileManager';
import { IEntity, ISpikes } from '../../Levels';
import { StateMachine } from '../../Base/StateMachine';
import { SpikesStateMachine } from './SpikesStateMachine';
import { randomById } from '../../Utils';
import EventManager from '../../Runtime/EventManager';
import DataManager from '../../Runtime/DataManager';
const { ccclass, property } = _decorator;

@ccclass('SpikesManager')
export class SpikesManager extends Component {
    /**实体的唯一ID */
    id: string = randomById(10)
    x: number = 0
    y: number = 0

    fsm: StateMachine
    /**当前地刺点数 */
    private _count: number
    /**总地刺点数 */
    private _totalCount: number
    /**类型 */
    public _type: ENTITY_TYPE_ENUM

    get count() {
        return this._count
    }
    set count(newCount: number) {
        if (this._count === newCount) return;
        this._count = newCount
        this.fsm.setParams(PARAMS_NAME_ENUM.SPIKES_CUR_COUNT, newCount)
    }

    get totalCount() {
        return this._totalCount
    }
    set totalCount(newTotalCount: number) {
        if (this._totalCount === newTotalCount) return;
        this._totalCount = newTotalCount
        this.fsm.setParams(PARAMS_NAME_ENUM.SPIKES_TOTAL_COUNT, newTotalCount)
    }

    async init(params: ISpikes) {
        const sprite = this.addComponent(Sprite);
        sprite.sizeMode = Sprite.SizeMode.CUSTOM;

        const transform = this.getComponent(UITransform);
        transform.setContentSize(TILE_WIDTH * 4, TILE_HEIGHT * 4);

        this.fsm = this.addComponent(SpikesStateMachine)
        await this.fsm.init()
        this.x = params.x
        this.y = params.y
        this._type = params.type
        this.count = params.count
        this.totalCount = SPIKES_TYPE_MAP_TOTAL_COUNT_ENUM[this._type]

        /**监听玩家移动方法 */
        EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.playerMoveEnd, this)
    }

    playerMoveEnd() {
        if (this.count === this.totalCount) {
            this.count = 1
        } else {
            this.count++;
        }
        this.onAttack()
    }

    /**攻击玩家 */
    onAttack() {
        if (!DataManager.Instance.player) {
            return;
        }
        const { x: playerX, y: playerY } = DataManager.Instance.player
        if (this.x === playerX && this.y === playerY && this.count === this.totalCount) {
            EventManager.Instance.emit(EVENT_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.DEATH)
        }
    }

    update() {
        this.node.setPosition(this.x * TILE_WIDTH - TILE_WIDTH * 1.5, -this.y * TILE_HEIGHT + TILE_HEIGHT * 1.5)
    }

    onDestroy() {
        EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.playerMoveEnd)
    }





}


